<template>
  <div class="game-container">
    <div class="score">得分: {{ score }}</div>
    <div class="controls">
      <button @click="startOrPauseGame" :disabled="!isPaused">开始</button>
      <button @click="resetGame">充值</button>
    </div>
    <canvas ref="gameCanvas" :width="canvasWidth" :height="canvasHeight"></canvas>
  </div>
</template>

<script>
export default {
  data() {
    return {
      score: 0,
      gridSize: 20,
      canvasWidth: 600,
      canvasHeight: 600,
      snake: [{ x: 300, y: 300 }],
      food: { x: 0, y: 0 },
      direction: { x: 0, y: 0 },
      gameInterval: null,
      speed: 200, // 修改初始速度为200
      maxSpeed: 100, // 修改最大速度为100
      isPaused: true, // 初始化暂停状态为true
    };
  },
  mounted() {
    document.body.style.overflow = 'hidden';
    this.initGame();
    this.placeFood();
  },
  beforeDestroy() {
    document.body.style.overflow = '';
    clearInterval(this.gameInterval);
  },
  methods: {
    initGame() {
      const canvas = this.$refs.gameCanvas;
      this.ctx = canvas.getContext('2d');
      this.ctx.fillStyle = '#000';
      this.ctx.strokeStyle = '#fff';
      this.direction = { x: 0, y: 0 };
      this.snake = [{ x: 300, y: 300 }];
      this.score = 0;
      this.speed = 200; // 修改初始速度为200
      this.isPaused = true; // 初始化暂停状态为true
    },
    startGame() {
      if (!this.gameInterval) {
        this.gameInterval = setInterval(() => {
          this.update();
          this.draw();
        }, this.speed);
      }
    },
    pauseGame() {
      clearInterval(this.gameInterval);
      this.gameInterval = null;
      this.isPaused = true;
    },
    startOrPauseGame() {
      console.log('Before:', this.isPaused); // 添加调试信息
      if (this.isPaused) {
        this.startGame();
        this.isPaused = false;
      }
      console.log('After:', this.isPaused); // 添加调试信息
    },
    resetGame() {
      this.pauseGame();
      this.initGame();
      this.placeFood();
      this.startGame();
    },
    update() {
      const head = { x: this.snake[0].x + this.direction.x, y: this.snake[0].y + this.direction.y };
      this.snake.unshift(head);

      if (this.isFoodEaten()) {
        this.score += 10;
        this.placeFood();
        if (this.speed > this.maxSpeed) {
          this.speed -= 10; // 加速
        }
        clearInterval(this.gameInterval);
        this.gameInterval = setInterval(() => { // 仅更新游戏循环间隔，不重新开始游戏
          this.update();
          this.draw();
        }, this.speed);
      } else {
        this.snake.pop();
      }

      if (this.isOutOfBounds() || this.isSelfCollision()) {
        this.gameOver();
      }
    },
    draw() {
      this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
      this.ctx.fillStyle = '#00ff00';
      this.snake.forEach(segment => {
        this.ctx.fillRect(segment.x, segment.y, this.gridSize, this.gridSize);
        this.ctx.strokeRect(segment.x, segment.y, this.gridSize, this.gridSize);
      });

      this.ctx.fillStyle = '#ff0000';
      this.ctx.fillRect(this.food.x, this.food.y, this.gridSize, this.gridSize);
      this.ctx.strokeRect(this.food.x, this.food.y, this.gridSize, this.gridSize);
    },
    placeFood() {
      this.food.x = Math.floor(Math.random() * (this.canvasWidth / this.gridSize)) * this.gridSize;
      this.food.y = Math.floor(Math.random() * (this.canvasHeight / this.gridSize)) * this.gridSize;
    },
    isFoodEaten() {
      return this.snake[0].x === this.food.x && this.snake[0].y === this.food.y;
    },
    isOutOfBounds() {
      return (
        this.snake[0].x < 0 ||
        this.snake[0].x >= this.canvasWidth ||
        this.snake[0].y < 0 ||
        this.snake[0].y >= this.canvasHeight
      );
    },
    isSelfCollision() {
      for (let i = 1; i < this.snake.length; i++) {
        if (this.snake[i].x === this.snake[0].x && this.snake[i].y === this.snake[0].y) {
          return true;
        }
      }
      return false;
    },
    gameOver() {
      clearInterval(this.gameInterval);
      alert('游戏失败！');
      this.initGame();
      this.placeFood();
      this.startGame();
    },
    changeDirection(event) {
      const keyPressed = event.keyCode;
      const goingUp = this.direction.y === -this.gridSize;
      const goingDown = this.direction.y === this.gridSize;
      const goingRight = this.direction.x === this.gridSize;
      const goingLeft = this.direction.x === -this.gridSize;

      if (keyPressed === 37 && !goingRight) {
        this.direction = { x: -this.gridSize, y: 0 };
      }
      if (keyPressed === 38 && !goingDown) {
        this.direction = { x: 0, y: -this.gridSize };
      }
      if (keyPressed === 39 && !goingLeft) {
        this.direction = { x: this.gridSize, y: 0 };
      }
      if (keyPressed === 40 && !goingUp) {
        this.direction = { x: 0, y: this.gridSize };
      }
    },
  },
  created() {
    window.addEventListener('keydown', this.changeDirection);
  },
  destroyed() {
    window.removeEventListener('keydown', this.changeDirection);
  },
};
</script>

<style>
body {
  background: linear-gradient(135deg, #0f0c29 0%, #302b63 48%, #24243e 100%);
  margin: 0;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: 'Arial', sans-serif;
}

.game-container {
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  width: 600px;
  height: 600px;
  margin: 50px auto;
  position: relative;
  border: 4px solid #42b983;
  border-radius: 10px;
  box-shadow: 0 0 30px rgba(0, 0, 0, 0.7);
  overflow: hidden;
}

.score {
  position: absolute;
  top: 10px;
  left: 10px;
  font-size: 24px;
  color: #ffffff;
  font-family: 'Arial', sans-serif;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}

.controls {
  position: absolute;
  top: 10px;
  right: 10px;
}

.controls button {
  margin-left: 10px;
  padding: 10px 20px;
  font-size: 16px;
  color: #ffffff;
  background-color: #42b983;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}

.controls button:hover {
  background-color: #35495e;
}

canvas {
  background-color: #1a1a1a;
  display: block;
  margin: 0 auto;
  border: 2px solid #42b983;
  border-radius: 8px;
}

/* 添加一些动画效果 */
@keyframes glow {
  0% { box-shadow: 0 0 10px rgba(66, 185, 131, 0.5); }
  50% { box-shadow: 0 0 20px rgba(66, 185, 131, 1); }
  100% { box-shadow: 0 0 10px rgba(66, 185, 131, 0.5); }
}

.game-container {
  animation: glow 2s infinite;
}
</style>